import axios from 'axios';
import Promise from 'bluebird';

const instance = axios.create({
  baseURL: CONF.SERVER_URI,
  headers:{
    'content-type': 'application/json',
  },
});
const axiosData = function (res) {
  return res.data;
};
const preHandleError = function (res) {
  return res.data;
};

const selectedApi = axios.create({
  baseURL: '/selected',
  headers: { 'Content-Type': 'application/json' },
});
selectedApi.interceptors.response.use(axiosData);

let welfares;

const Module = {
  getShareData(id) {
    return Promise.all([
      Module.fetchProfile(id),
      Module.fetchPhotos(id,1),
      Module.fetchWelfares(),
      Module.fetchMyExp(id),
    ]).then((arr) => {
      var profile = arr[0];
       if (!profile.regard_important) profile.regard_important = '';
      profile._personWelfares = mapWelfares(profile.regard_important, arr[2]);
      profile.jobExps = arr[3];
      return arr;
    });
  },
  fetchProfile(id) {
    return instance.get('/users/' + id).then(axiosData).catch(preHandleError);
  },
  fetchMyExp(id) {
    return instance.get('/users/' + id + '/work_experiences').then(axiosData).catch(preHandleError);
  },
  fetchPhotos(id, role) {
    return instance.get('/users/' +id + '/photos?role=' + role).then(axiosData).catch(preHandleError);
  },
  fetchWelfares() {
    if(!welfares){
      welfares = instance.get('/welfares').then(axiosData).catch((err) => { welfares = null; preHandleError(err) });
    }
    return welfares;
  },
  fetchSelectedDetail(id, user_id) {
    let job;
    return Promise.all([
      Module.fetchWelfares(),
      selectedApi.get(`/v1/jobs/${id}`, {
        params: {
          user_id,
        },
      })
    ]).then((arr) => {
      const [welfares, j] = arr;
      job = j;
      job.welfareList = mapWelfares(job.welfare, welfares);
      return selectedApi.get(`/v1/admin/companies/${j.company_id}/photos`);
    }).then((photos) => {
      job.company.photos = photos;
      return job;
    });
  },
};

function mapWelfares (str, items) {
  const rtn = [];
  const arr = str.split(',');
  arr.forEach(function (jobNameId) {
    let name;
    for (let i = 0; i < items.length; i++) {
      if (items[i].id == jobNameId) {
        name = items[i];
        break;
      }
    }
    if (name) rtn.push(name);
  });
  return rtn;
}

export default Module;
